<?  
 require('phpQuery/phpQuery.php'); 
 $url='http://www.baijingapp.com/m/register/';
 $base_path='../m';//保存路径
 $file_name='register.php';//需要保存的文件名
 phpQuery::newDocumentFile($url); 

preg_match('/(.*\/\/\w+\.\w+\.\w{2,3})(\/|\/.*\/)(|\w+\.\w+)/',$url,$matches);
//var_dump($matches); die();
$yuming=$matches[1];
session_start();
$_SESSION['yuming']=$yuming;//域名
$_SESSION['content']=pq("");//获取页面原始代码
$_SESSION['base_path']=$base_path; //要保存的根目录
$_SESSION['file_path']=$matches[1].$matches[2]; //要采集的文件的目录
$_SESSION['file_name']=$file_name; //要保存的文件名
//echo $_SESSION['file_path'];

class caiji {

    //采集
     function cai($saveName){
        //路径字符串替换并保存文件

        $this->findCss();
        $this->findJs();
        $this->findImg();
        //$this->test();
        $this->save($_SESSION['base_path'].'/'.$_SESSION['file_name'],$_SESSION['content']);
     }

     //寻找CSS文件，按路径保存并替换路径
     function findCss(){
        $item=pq("link");
        foreach($item as $value) {
              //获取文件目录
              $path=$value->getAttribute('href');
              if($path!=""){

                   //获取文件名称
                    $fileName=basename($path);
                    $fileName=preg_replace('/(\w+\.\w+)(.*)/','$1'."",$fileName);
                    //正则表达式
                    $perl='/(<link.+href="|\')('.addcslashes($path,'/,?').')("|\')/i';
                    //按路径获取文件内容
                    $string=$this->getstring($path,$fileName,$perl,'css');
                    
              }  

        } 

     }
      
    
     //寻找Js文件，按路径保存并替换路径
     function findJs(){
        $js=pq("script");
        foreach($js as $value) {
              //获取文件目录
              $path=$value->getAttribute('src');
              if($path!=""){
                   //获取文件名称
                    $fileName=basename($path);
                    $fileName=preg_replace('/(\w+\.js)(.*)/','$1'."",$fileName);
                    //正则表达式
                    $perl='/(<script.+src="|\')('.addcslashes($path,'/,?').')("|\')/i';
                    //按路径获取文件内容
                    $string=$this->getstring($path,$fileName,$perl,'js');
              }  

        } 

     }

     //寻找图片文件，按路径保存并替换路径
     function findImg(){
        $item=pq("img");
        foreach($item as $value) {
              //获取文件目录
              $path=$value->getAttribute('src');
              if($path!=""){

                   //获取文件名称
                    $fileName=basename($path);
                    //正则表达式
                    $perl='/(<img.+src="|\')('.addcslashes($path,'/').')("|\')/i';
                    //按路径获取文件内容
                    $string=$this->getstring($path,$fileName,$perl,'image');
                    
              }  

        } 

     }

     //获取并替换字符串
     function getstring($path,$fileName,$perl,$type){
          $status=0;
          $path2=$path;
          $fileContent='';
          if(preg_match('/.*\/\/\w+.\w+.\w{2,5}/',$path)){
                $status=0;//域名或者ip路径
                $available_path=$path;
                $path=preg_replace('/.*\/\/\w+.\w+.\w{2,5}/','.',$path);
          }elseif(preg_match('/^\//',$path)){
                $status=1; //根目录路径
                $available_path=$_SESSION['file_path'].$path;
                $path='.'.$path;
                
          }elseif(preg_match('/^\./',$path)){
                $status=2; //相对目录路径
                $available_path=$_SESSION['file_path'].$path;
          }
          $fileContent=@file_get_contents($available_path);


          if($type=="image"){
                //按目录保存图片
                $dir= $_SESSION['base_path'].dirname($path);
                 //echo $dir.'<br />';
                if(!is_dir($dir)){
                     mkdir($dir,0777,true);
                }
                //$this->creatImage($available_path, $dir.'/'.$fileName);
                $this->getImg($available_path, $dir.'/'.$fileName);
          }else{
                if($type=="css"){
                    $prel='/background: url\((.+)\)/';
                    preg_match_all($prel,$fileContent,$matchh); 
                    $imgarray=$matchh[1];
                    $_SESSION['background']=$fileContent;
                    //$imgarray：图片路径数组,$path2：css文件采集路径,$path：css文件存放路径
                    $this->findBackgroundImg($imgarray,$path2,$path);
                    $fileContent=$_SESSION['background'];
                }
                //按目录保存content
                $this->saveContent($path,$fileName,$fileContent);
          }
         
          

          //替换主文件里的目录
           if($status==0 || $status==1){
              //把域名换掉
               $param_replace='$1'.$path.'$3';
               $_SESSION['content']=preg_replace($perl,$param_replace,$_SESSION['content']);
          }

     }
     //背景图片
     function findBackgroundImg($backarray,$path2,$path){
          $css_original_path=dirname($path2);
          $css_save_path=dirname($path);

          foreach($backarray as $value){
                if(preg_match('/.*\/\/\w+.\w+.\w{2,5}/',$value)){
                      $status=0;//域名或者ip路径
                      $available_path=$value;
                      $value=preg_replace('/.*\/\/\w+.\w+.\w{2,5}/','.',$value);
                      $savepath=$_SESSION['base_path'].'/'.$value;
                }elseif(preg_match('/^\//',$value)){
                      $status=1; //根目录路径
                      $available_path=$_SESSION['yuming'].'/'.$value;
                      $value='.'.$value;
                      $savepath=$_SESSION['base_path'].'/'.$value;
                      
                }else{
                      $status=2; //相对目录路径
                      $available_path=$_SESSION['yuming'].'/'.$css_original_path.'/'.$value;
                      $savepath=$_SESSION['base_path'].'/'.$css_save_path.'/'.$value;
                }
                $dir=dirname($savepath.'/');
                if(!is_dir($dir)){
                     mkdir($dir,0777,true);
                }
                //按目录生成图片
                $this->getImg($available_path, $savepath);
                if($status==0 || $status==1){
                    //把图片路径替换
                     $prel='/(background: url\()('.addcslashes($value,'/,?').')(\))/';
                     $param_replace='$1'.$savepath.'$3';
                     $_SESSION['background']=preg_replace($perl,$param_replace,$_SESSION['background']);
                }
               
               
          
          }
          
     }
     // function findBackgroundImg($backarray,$path2,$path){
     //      foreach($backarray as $value){
     //           $status=0;
     //           $fileName=basename($path);
     //           if(preg_match('/.*\/\/\w+.\w+.\w{2,5}/',$value)){
     //                  $status=0;//域名或者ip路径
     //                  $available_path=$value;
     //                  $value=preg_replace('/.*\/\/\w+.\w+.\w{2,5}/','.',$value);
     //            }elseif(preg_match('/^\//',$value)){
     //                  $status=1; //根目录路径
     //                  $available_path=$_SESSION['yuming'].'/'.$value;
     //                  $value='.'.$value;
                      
     //            }elseif(preg_match('/^\./',$value)){
     //                  $status=2; //相对目录路径
     //                  $available_path=$path2.$value;
                      
     //            }
     //            $dir= $path.dirname($value);
     //            echo $dir.'<br />';
     //            if(!is_dir($dir)){
     //                 mkdir($dir,0777,true);
     //            }
     //            //按目录生成图片
     //            $this->getImg($available_path, $dir.'/'.$fileName);
     //            if($status==0 || $status==1){
     //                //把域名换掉
     //                 $prel='/(background: url\()('.addcslashes($path2,'/,?').')(\))/';
     //                 $param_replace='$1'.$path.'$3';
     //                 $_SESSION['background']=preg_replace($perl,$param_replace,$_SESSION['background']);
     //            }
          
     //      }
          
     // }
     function test(){
          $this->creatImage('http://www.xiakenet.com//Public/home/images/caseimg/001s.jpg','../content/aa.jpg' );
     }
     //生成图片
     function creatImage($url,$filename) { 
            if($url == '') { 
            return; //如果 $url 为空则返回 false; 
            } 
            $ext_name = strrchr($url, '.'); //获取图片的扩展名 
            if($ext_name != '.gif' && $ext_name != '.jpg' && $ext_name != '.bmp' && $ext_name != '.png') { 
            return; //格式不在允许的范围 
            } 
            if($filename == '') { 
            $filename = time().$ext_name; //以时间戳另起名 
            } 
            //开始捕获 
            ob_start(); 
            readfile($url); 
            $img_data = ob_get_contents(); 
            ob_end_clean(); 
            $size = strlen($img_data); 
            $local_file = fopen($filename , 'a'); 
            fwrite($local_file, $img_data); 
            fclose($local_file); 
            //return $filename; 
     }
     function getImg($url = "", $filename = "")
    {
            //去除URL连接上面可能的引号
            //$url = preg_replace( '/(?:^['"]+|['"/]+$)/', '', $url );
            $hander  = curl_init();
            $fp = @fopen($filename,'wb');
            if($fp){
                  curl_setopt($hander,CURLOPT_URL,$url);
                  curl_setopt($hander,CURLOPT_FILE,$fp);
                  curl_setopt($hander,CURLOPT_HEADER,0);
                  curl_setopt($hander,CURLOPT_FOLLOWLOCATION,1);
                  //curl_setopt($hander,CURLOPT_RETURNTRANSFER,false);//以数据流的方式返回数据,当为false是直接显示出来
                  curl_setopt($hander,CURLOPT_TIMEOUT,60);
                  curl_exec($hander);
                  curl_close($hander);
                  fclose($fp);
                  
            }
            return true;
            
    }

     //按目录并保存
     function saveContent($path,$fileName,$fileContent){
            //拼接路径
            $dir= $_SESSION['base_path'].dirname($path);
            if(!is_dir($dir)){
                 mkdir($dir,0777,true);

            }
            //保存路径
            $savePath=$dir.'/'.$fileName;
            $this->save($savePath,$fileContent);

     }
     //保存
     function save($path,$content){
          if(!file_exists($path)){
               $handle=fopen($path,'w+'); 
               fwrite($handle,$content);
          }
        
     }
     
}

$caiji=new caiji();
$caiji->cai('index.php');